var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var check = require('../../../utils/check.js');
var area = require('../../../utils/area.js');

var app = getApp();
Page({
    data: {
        address: {
            id: '',
            areaCode: 0,
            address: '',
            name: '',
            tel: '',
            isDefault: 0,
            province: '',
            city: '',
            county: '',
            userId: wx.getStorageSync('userInfo').id
        },
        addressId: 0,
        openSelectRegion: false,
        selectRegionList: [{
                code: 0,
                name: '省份'
            },
            {
                code: 0,
                name: '城市'
            },
            {
                code: 0,
                name: '区县'
            }
        ],
        regionType: 1,
        regionList: [],
        selectRegionDone: false
    },
    bindinputMobile(event) {
        let address = this.data.address;
        address.tel = event.detail.value;
        this.setData({
            address: address
        });
    },
    bindinputName(event) {
        let address = this.data.address;
        address.name = event.detail.value;
        this.setData({
            address: address
        });
    },
    bindinputAddress(event) {
        let address = this.data.address;
        address.addressDetail = event.detail.value;
        this.setData({
            address: address
        });
    },
    bindIsDefault() {
        let address = this.data.address;
        address.isDefault = !address.isDefault;
        this.setData({
            address: address
        });
    },
    getAddressDetail() {
        let that = this;
        util.request(api.AddressDetail, {
            id: that.data.addressId
        }).then(function(res) {
            if (res.errno === 0) {
                if (res.data) {
                    that.setData({
                        address: res.data
                    });
                }
            }
        });
    },
    setRegionDoneStatus() {
        let that = this;
        let doneStatus = that.data.selectRegionList.every(item => {
            return item.code != 0;
        });

        that.setData({
            selectRegionDone: doneStatus
        })

    },
    chooseRegion() {
        let that = this;
        this.setData({
            openSelectRegion: !this.data.openSelectRegion
        });

        //设置区域选择数据
        let address = this.data.address;
        if (address.areaCode > 0) {
            let selectRegionList = this.data.selectRegionList;
            selectRegionList[0].code = address.areaCode.slice(0, 2) + '0000';
            selectRegionList[0].name = address.province;

            selectRegionList[1].code = address.areaCode.slice(0, 4) + '00';
            selectRegionList[1].name = address.city;

            selectRegionList[2].code = address.areaCode;
            selectRegionList[2].name = address.county;

            let regionList = area.getList('county', address.areaCode.slice(0, 4));
            regionList = regionList.map(item => {
                //标记已选择的
                if (address.areaCode === item.code) {
                    item.selected = true;
                } else {
                    item.selected = false;
                }
                return item;
            })

            this.setData({
                selectRegionList: selectRegionList,
                regionType: 3,
                regionList: regionList
            });

        } else {
            let selectRegionList = [{
                    code: 0,
                    name: '省份',
                },
                {
                    code: 0,
                    name: '城市',
                },
                {
                    code: 0,
                    name: '区县',
                }
            ];

            this.setData({
                selectRegionList: selectRegionList,
                regionType: 1,
                regionList: area.getList('province')
            });
        }

        this.setRegionDoneStatus();

    },
    openLocation() {
        wx.navigateTo({
            url: '/pages/map/map'
        });
    },
    testLocation: function() {
        wx.showToast({
            title: '正在获取位置...',
            icon: 'loading',
            duration: 1000
        });

        let that = this;
        // 直接调用微信小程序的位置选择接口
        wx.chooseLocation({
            success: function(res) {
                console.log("位置信息:", res);
                if (res.address) {
                    // 处理地址信息
                    let address = that.data.address;

                    // 保存详细地址
                    address.addressDetail = res.name;

                    // 解析省市区
                    let addressComponents = that.parseLocationAddress(res.address);
                    address.province = addressComponents.province;
                    address.city = addressComponents.city;
                    address.county = addressComponents.district;

                    // 查找匹配的区域码
                    that.findAreaCodeByName(address);

                    // 更新数据
                    that.setData({
                        address: address
                    });

                    wx.showToast({
                        title: '位置获取成功',
                        icon: 'success'
                    });
                }
            },
            fail: function(err) {
                console.log("选择位置失败:", err);
                wx.showToast({
                    title: '获取位置失败',
                    icon: 'none'
                });
            }
        });
    },

    // 解析高德地图返回的地址
    parseLocationAddress: function(address) {
        console.log("解析地址:", address);

        // 初始化结果
        let result = {
            province: '',
            city: '',
            district: ''
        };

        // 处理直辖市
        const municipalities = ['北京', '上海', '天津', '重庆'];

        try {
            // 尝试直接用正则匹配省市区
            let provinceMatch = address.match(/(.*?)[省]/);
            let cityMatch = address.match(/[省](.*?)[市]/);
            let districtMatch = address.match(/[市](.*?)[区县]/);

            // 处理直辖市特殊情况
            let isMunicipality = false;
            for (let i = 0; i < municipalities.length; i++) {
                if (address.indexOf(municipalities[i]) === 0) {
                    isMunicipality = true;
                    result.province = municipalities[i];
                    result.city = municipalities[i] + '市';

                    // 提取区
                    let districtMatch = address.match(new RegExp(municipalities[i] + '市(.*?)[区县]'));
                    if (districtMatch && districtMatch[1]) {
                        result.district = districtMatch[1] + '区';
                    }
                    break;
                }
            }

            // 处理普通省市区
            if (!isMunicipality) {
                if (provinceMatch && provinceMatch[1]) {
                    result.province = provinceMatch[1] + '省';
                }

                if (cityMatch && cityMatch[1]) {
                    result.city = cityMatch[1] + '市';
                } else if (address.match(/(.*?)[市]/)) {
                    // 如果没有找到省，可能直接以市开头
                    let directCityMatch = address.match(/(.*?)[市]/);
                    if (directCityMatch && directCityMatch[1]) {
                        result.city = directCityMatch[1] + '市';
                    }
                }

                if (districtMatch && districtMatch[1]) {
                    result.district = districtMatch[1] + '区';
                } else {
                    // 尝试匹配县
                    let countyMatch = address.match(/[市](.*?)[县]/);
                    if (countyMatch && countyMatch[1]) {
                        result.district = countyMatch[1] + '县';
                    } else if (address.match(/(.*?)[区]/)) {
                        // 直接匹配区
                        let directDistrictMatch = address.match(/(.*?)[区]/);
                        if (directDistrictMatch && directDistrictMatch[1]) {
                            result.district = directDistrictMatch[1] + '区';
                        }
                    } else if (address.match(/(.*?)[县]/)) {
                        // 直接匹配县
                        let directCountyMatch = address.match(/(.*?)[县]/);
                        if (directCountyMatch && directCountyMatch[1]) {
                            result.district = directCountyMatch[1] + '县';
                        }
                    }
                }
            }

            // 如果未能提取出完整地址，使用备用方法
            if (!result.province || !result.city) {
                let parts = address.split(/[省市区县]/);
                if (parts.length >= 3) {
                    if (!result.province) result.province = parts[0] + '省';
                    if (!result.city) result.city = parts[1] + '市';
                    if (!result.district) result.district = parts[2] + '区';
                }
            }

            console.log("解析结果:", result);
        } catch (error) {
            console.error("地址解析出错:", error);
        }

        return result;
    },

    // 通过省市区名称查找区域代码
    findAreaCodeByName: function(address) {
        if (!address.province || !address.city || !address.county) {
            return;
        }

        let that = this;
        // 获取省级列表
        util.request(api.RegionList, {
            parentId: 0
        }).then(function(res) {
            if (res.errno === 0) {
                let provinceList = res.data;
                // 查找省份
                for (let i = 0; i < provinceList.length; i++) {
                    if (provinceList[i].name.indexOf(address.province) >= 0 || address.province.indexOf(provinceList[i].name) >= 0) {
                        // 找到匹配的省份
                        let provinceCode = provinceList[i].code;
                        // 获取城市列表
                        util.request(api.RegionList, {
                            parentId: provinceCode
                        }).then(function(cityRes) {
                            if (cityRes.errno === 0) {
                                let cityList = cityRes.data;
                                // 查找城市
                                for (let j = 0; j < cityList.length; j++) {
                                    if (cityList[j].name.indexOf(address.city) >= 0 || address.city.indexOf(cityList[j].name) >= 0) {
                                        // 找到匹配的城市
                                        let cityCode = cityList[j].code;
                                        // 获取区县列表
                                        util.request(api.RegionList, {
                                            parentId: cityCode
                                        }).then(function(countyRes) {
                                            if (countyRes.errno === 0) {
                                                let countyList = countyRes.data;
                                                // 查找区县
                                                for (let k = 0; k < countyList.length; k++) {
                                                    if (countyList[k].name.indexOf(address.county) >= 0 || address.county.indexOf(countyList[k].name) >= 0) {
                                                        // 找到匹配的区县
                                                        let countyCode = countyList[k].code;
                                                        // 更新地址信息
                                                        let addressData = that.data.address;
                                                        addressData.areaCode = countyCode;
                                                        that.setData({
                                                            address: addressData,
                                                            selectRegionList: [{
                                                                code: provinceCode,
                                                                name: provinceList[i].name
                                                            }, {
                                                                code: cityCode,
                                                                name: cityList[j].name
                                                            }, {
                                                                code: countyCode,
                                                                name: countyList[k].name
                                                            }],
                                                            selectRegionDone: true
                                                        });
                                                        return;
                                                    }
                                                }
                                            }
                                        });
                                        return;
                                    }
                                }
                            }
                        });
                        return;
                    }
                }
            }
        });
    },
    onLoad: function(options) {
        // 页面初始化 options为页面跳转所带来的参数
        console.log(options)
        if (options.id && options.id != 0) {
            this.setData({
                addressId: options.id
            });
            this.getAddressDetail();
        }

        this.getRegionList(1);
    },
    onReady: function() {

    },
    selectRegionType(event) {
        let that = this;
        let regionTypeIndex = event.target.dataset.regionTypeIndex;
        let selectRegionList = that.data.selectRegionList;

        //判断是否可点击
        if (regionTypeIndex + 1 == this.data.regionType || (regionTypeIndex - 1 >= 0 && selectRegionList[regionTypeIndex - 1].code <= 0)) {
            return false;
        }

        let selectRegionItem = selectRegionList[regionTypeIndex];
        let code = selectRegionItem.code;
        let regionList;
        if (regionTypeIndex === 0) {
            // 点击省级，取省级
            regionList = area.getList('province');
        } else if (regionTypeIndex === 1) {
            // 点击市级，取市级
            regionList = area.getList('city', code.slice(0, 2));
        } else {
            // 点击县级，取县级
            regionList = area.getList('county', code.slice(0, 4));
        }

        regionList = regionList.map(item => {
            //标记已选择的
            if (that.data.selectRegionList[regionTypeIndex].code == item.code) {
                item.selected = true;
            } else {
                item.selected = false;
            }
            return item;
        })

        this.setData({
            regionList: regionList,
            regionType: regionTypeIndex + 1
        })

        this.setRegionDoneStatus();
    },
    selectRegion(event) {
        let that = this;
        let regionIndex = event.target.dataset.regionIndex;
        let regionItem = this.data.regionList[regionIndex];
        let regionType = this.data.regionType;
        let selectRegionList = this.data.selectRegionList;
        selectRegionList[regionType - 1] = regionItem;

        if (regionType == 3) {
            this.setData({
                selectRegionList: selectRegionList
            })

            let regionList = that.data.regionList.map(item => {
                //标记已选择的
                if (that.data.selectRegionList[that.data.regionType - 1].code == item.code) {
                    item.selected = true;
                } else {
                    item.selected = false;
                }
                return item;
            })

            this.setData({
                regionList: regionList
            })

            this.setRegionDoneStatus();
            return
        }

        //重置下级区域为空
        selectRegionList.map((item, index) => {
            if (index > regionType - 1) {
                item.code = 0;
                item.name = index == 1 ? '城市' : '区县';
            }
            return item;
        });

        this.setData({
            selectRegionList: selectRegionList,
            regionType: regionType + 1
        })

        let code = regionItem.code;
        let regionList = [];
        if (regionType === 1) {
            // 点击省级，取市级
            regionList = area.getList('city', code.slice(0, 2))
        } else {
            // 点击市级，取县级
            regionList = area.getList('county', code.slice(0, 4))
        }

        this.setData({
            regionList: regionList
        })

        this.setRegionDoneStatus();
    },
    doneSelectRegion() {
        if (this.data.selectRegionDone === false) {
            return false;
        }

        let address = this.data.address;
        let selectRegionList = this.data.selectRegionList;
        address.province = selectRegionList[0].name;
        address.city = selectRegionList[1].name;
        address.county = selectRegionList[2].name;
        address.areaCode = selectRegionList[2].code;

        this.setData({
            address: address,
            openSelectRegion: false
        });

    },
    cancelSelectRegion() {
        this.setData({
            openSelectRegion: false,
            regionType: this.data.regionDoneStatus ? 3 : 1
        });

    },
    cancelAddress() {
        wx.navigateBack();
    },
    saveAddress() {
        console.log(this.data.address)
        let address = this.data.address;

        if (address.name == '') {
            util.showErrorToast('请输入姓名');

            return false;
        }

        if (address.tel == '') {
            util.showErrorToast('请输入手机号码');
            return false;
        }


        if (address.areaCode == 0) {
            util.showErrorToast('请输入省市区');
            return false;
        }

        if (address.addressDetail == '') {
            util.showErrorToast('请输入详细地址');
            return false;
        }

        let that = this;
        wx.request({
            url: 'http://localhost:9260/wx/address/save',
            method: 'POST',
            data: {
                id: address.id,
                name: address.name,
                tel: address.tel,
                province: address.province,
                city: address.city,
                county: address.county,
                areaCode: address.areaCode,
                addressDetail: address.addressDetail,
                isDefault: address.isDefault,
                userId: wx.getStorageSync('userInfo').id
            },
            success: function(res) {
                console.log(res)
                if (res.data.errno === 0) {
                    //返回之前，先取出上一页对象，并设置addressId
                    var pages = getCurrentPages();
                    var prevPage = pages[pages.length - 2];
                    console.log(prevPage);
                    if (prevPage.route == "pages/checkout/checkout") {
                        prevPage.setData({
                            addressId: res.data
                        })

                        try {
                            wx.setStorageSync('addressId', res.data);
                        } catch (e) {

                        }
                        console.log("set address");
                    }
                    wx.navigateBack();
                }
            }
        });

    },
    onShow: function() {
        // 页面显示
        let that = this;
        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1];

        // 检查是否从地图选择页面返回的数据
        if (currPage.data.address &&
            typeof currPage.data.address.full !== 'undefined' &&
            currPage.data.address.latitude &&
            currPage.data.address.longitude) {

            let mapAddress = currPage.data.address;
            let address = that.data.address;

            // 保存详细地址
            address.addressDetail = mapAddress.name || mapAddress.full;

            // 保存省市区
            address.province = mapAddress.province;
            address.city = mapAddress.city;
            address.county = mapAddress.county;

            // 更新数据
            that.setData({
                address: address
            });

            // 重新查找区域代码
            that.findAreaCodeByName(address);

            wx.showToast({
                title: '位置获取成功',
                icon: 'success'
            });
        }
    },
    onHide: function() {
        // 页面隐藏

    },
    onUnload: function() {
        // 页面关闭

    },
    // 返回上一页
    goBack: function() {
        wx.navigateBack({
            delta: 1
        });
    },
    getRegionList(regionType, regionCode, callback) {
        let that = this;
        let regionList = [];

        util.request(api.RegionList, {
            parentId: regionCode || 0
        }).then(function(res) {
            if (res.errno === 0) {
                regionList = res.data.map(item => {
                    return {
                        id: item.id,
                        name: item.name,
                        code: item.code,
                        type: item.type,
                        selected: false
                    };
                });

                regionList.unshift({
                    id: 0,
                    name: '请选择',
                    code: 0,
                    type: 0,
                    selected: false
                });

                if (callback && typeof callback === 'function') {
                    callback(regionList);
                } else {
                    that.setData({
                        regionList: regionList
                    });
                }
            }
        });
    }
})